<template>
  <div class="operation-contain">
    <div class="operation-btn">
      <el-button type="primary" size="mini" @click="expand">展开/折叠</el-button>
      <el-button type="primary" size="mini" @click="check('all')">全选</el-button>
      <el-button type="primary" size="mini" @click="check('not')">全不选</el-button>
    </div>
    <el-tree
      :data="list.data"
      show-checkbox
      node-key="id"
      :props="defaultProps"
      :expand-on-click-node="false"
      :check-on-click-node="true"
      :default-expand-all="list.isExpand"
      v-loading="list.loading"
      ref="tree"
      @check-change="checkChange">
    </el-tree>
    <div class="footer-btn">
      <el-button @click="cancel" size="medium">取 消</el-button>
      <el-button v-perms="'system:role:setRoleMenu'" type="primary" @click="sure" :loading="loading" size="medium">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { resetRouter, constRoutes } from '@/router/index'
export default {
  data () {
    return {
      list: {
        data: [],
        page: 1,
        size: 1000,
        loading: false,
        isExpand: true
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      loading:false,
      defaultChecks: [],
      menus: [],
      menuChecks: []
    }
  },
  mounted () {
    this.getMenuList()
  },
  methods: {
    ...mapActions({
      getURoutes: 'user/getURoutes',
      finalRoutes: 'user/setFinalURoutes'
    }),
    detali () { // 根据id获取角色下的菜单权限列表和接口权限列表详情
      this.$API({
        name: 'detailRole',
        paths: [this.$route.params.id],
        requireAuth: true
      }).then (res => {
        if (res.data.code === 200) {
          this.menus = res.data.data.menus
          this.defaultChecked()
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch(error => {
        this.$message.error(error)
      })
    },
    defaultChecked () { // 默认选中
      this.$nextTick(() => {
        const arr = []
        this.menus.forEach(item => {
          if (this.$refs.tree && (!this.$refs.tree.getNode(item.id).childNodes || !this.$refs.tree.getNode(item.id).childNodes.length)) {
            arr.push(item.id)
          }
        })
        this.defaultChecks = arr
        this.$refs.tree && this.$refs.tree.setCheckedKeys(arr)
      })
    },
    expand () { // 展开/折叠
      this.list.isExpand = !this.list.isExpand
      const nodes = this.$refs.tree.store._getAllNodes()
      for (let i in nodes) {
        nodes[i].expanded = this.list.isExpand
      }
    },
    check (type) { // 全选或全不选
      switch (type) {
        case 'all':
          this.$refs.tree.setCheckedNodes(this.list.data)
        break
        case 'not':
          this.$refs.tree.setCheckedKeys([])
        break
      }
    },
    checkChange () { // 节点选中状态发生变化时的回调
      this.$nextTick(() => {
        this.menuChecks = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
      })
    },
    getMenuList () { // 获取所有菜单列表
      this.list.loading = true
      this.$API({
        name: 'getMenuList',
        params: {
          page: this.list.page,
          size: this.list.size,
          status: true
        },
        requireAuth: true
      }).then (res => {
        if (res.data.code === 200) {
          this.list.data = res.data.data.data
          this.detali()
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch(error => {
        this.$message.error(error)
      }).finally(() => {
        this.list.loading = false
      })
    },
    cancel () { // 取消
      this.$router.push({ path: '/system/role' })
    },
    async sure () { // 确定
      this.loading = true
      if (this.menuChecks.length === 0) {
        this.menuChecks = this.defaultChecks
      }
      const res = await this.$API({
        name: 'setRoleMenu',
        requireAuth: true,
        data: {
          roleId: this.$route.params.id,
          menuIds: this.menuChecks
        }
      })
      if (res.data.code === 200) {
        this.loading = false
        this.getMenuList()
        this.$notify.success('授权成功')
        // 重置路由并更新路由
        resetRouter()
        const routes = await this.getURoutes()
        routes.push({
          path: '*',
          redirect: '/404',
          meta: {
            title: '404',
            is_frame: 0,
            icon: '',
            hidden: 0
          }
        })
        this.finalRoutes([...constRoutes, ...routes])
        this.$router.addRoutes(routes)
      } else {
        this.$message.error(res.data.msg)
      }
    }
  }
}
</script>


<style lang="scss" >
.operation-contain {
  // 修改el-tree 的图标
  .el-icon-caret-right::before {
    content: "\e723";
    font-size: 14px;
  }
}
</style>
<style lang="scss" scoped>
// 修改el-tree 的图标
.el-icon-caret-right::before {
  content: "\e723";
  font-size: 14px;
}
.operation-contain {
  height: 100%;
  display: flex;
  flex-direction: column;
  .operation-btn {
    margin-bottom: 15px;
    flex-shrink: 0;
  }
  .footer-btn {
    flex-shrink: 0;
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }
  .el-tree {
    flex: 1 1 auto;
    overflow-y: auto;
  }
}
</style>